﻿///***************************************************************
/// 시  스  템 : Updms.Com
/// 단위시스템 : COM
/// 계      층 : Presentation Layer
/// 프로그램명 : Com1019m
/// 파  일  명 : Com1019m.aspx.cs
/// 설      명 : 프로그램별 그리드라벨관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2011-02-15 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Com.Exe;



namespace Updms.Com
{
	public partial class Com1019m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Com1019m";
		public static readonly string gs_path_info = "/updms/Com/" + PID + ".aspx";

		Global global = new Global();

		//검색
		protected string kw1 = "";	//프로그램

		//메뉴 선택값
		protected string gs_sm = "";

		// 페이지모드
		private string gs_page_mode = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetPgmId();
			SetLabelInitial();
			SetLabelId();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			ddl_search_pgm_id.Attributes.Add("onChange", "chkDisableOption(this)");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
			{
				kw1 = ddl_search_pgm_id.SelectedValue;
			}
			else
			{
				kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
				ddl_search_pgm_id.SelectedValue = kw1;
			}
		}

		#endregion

		#region 마스터 Method (SetPgmId)

		private void SetPgmId()
		{
			using (Com1011m_NT _Com1011m_NT = new Com1011m_NT())
			{
				ddl_search_pgm_id.DataSource = _Com1011m_NT.GetSystemNPgmList(LANG_SET);
				ddl_search_pgm_id.DataMember = "UPDMS_COM_PGM";
				ddl_search_pgm_id.DataTextField = "Pgm_Nm";
				ddl_search_pgm_id.DataValueField = "Pgm_Id";
				ddl_search_pgm_id.DataBind();
			}
		}

		#endregion

		#region 디테일 Method (SetLabelInitial, SetLabelId, SetGridColumn)

		private void SetLabelInitial()
		{
			DataSet ds = new DataSet();
			DataTable dt = new DataTable();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_lang_set", typeof(string), "ko");
			lo_dp.AddProperty("ls_initial", typeof(string), "");

			Com1017m_NT _Com1017m_NT = new Com1017m_NT();

			ds.Merge(_Com1017m_NT.GetListForCtrlBinding(lo_dp));

			dt = ds.Tables["UPDMS_COM_LABEL"].DefaultView.ToTable("UPDMS_COM_LABEL", true, "Initial");

			// 검색
			ddl_label_initial.Items.Clear();
			ddl_label_initial.DataSource = dt;
			ddl_label_initial.DataMember = "UPDMS_COM_LABEL";
			ddl_label_initial.DataTextField = "Initial";
			ddl_label_initial.DataValueField = "Initial";
			ddl_label_initial.DataBind();
			ddl_label_initial.Items.Insert(0, new ListItem(DDL_TOTAL, ""));

			//자주사용되는 라벨을 별도로 조회하도록 함
			ddl_label_initial.Items.Insert(ddl_label_initial.Items.Count, new ListItem("Weekend", "Weekend"));
			ddl_label_initial.Items.Insert(ddl_label_initial.Items.Count, new ListItem("Calendar", "Calendar"));
			ddl_label_initial.Items.Insert(ddl_label_initial.Items.Count, new ListItem("GridView", "GridView"));
			ddl_label_initial.Items.Insert(ddl_label_initial.Items.Count, new ListItem("Button", "Button"));
		}

		//라벨DDL바인딩
		private void SetLabelId()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_lang_set", typeof(string), "ko");
			lo_dp.AddProperty("ls_initial", typeof(string), ddl_label_initial.SelectedValue);

			Com1017m_NT _Com1017m_NT = new Com1017m_NT();

			lo_ds.Merge(_Com1017m_NT.GetListForCtrlBinding(lo_dp));

			// 검색
			ddl_label_id.Items.Clear();
			ddl_label_id.DataSource = lo_ds;
			ddl_label_id.DataMember = "UPDMS_COM_LABEL";
			ddl_label_id.DataTextField = "Text";
			ddl_label_id.DataValueField = "Value";
			ddl_label_id.DataBind();
			ddl_label_id.Items.Insert(0, new ListItem(DDL_SELECT, ""));
			ddl_label_id.Items.Insert(1, new ListItem("Empty Data", "0"));
		}

		//그리드컬럼 바인딩
		private void SetGridColumn(string ps_grid_id)
		{
			DataPack lo_dp = new DataPack();
			DataSet lo_ds = new DataSet();

			lo_dp.AddProperty("ls_pgm_id", typeof(string), ddl_search_pgm_id.SelectedValue);
			lo_dp.AddProperty("ls_grid_id", typeof(string), ps_grid_id);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Com1019m_NT _Com1019m_NT = new Com1019m_NT())
			{
				lo_ds.Merge(_Com1019m_NT.GetColumnListByPgmIdNGridId(lo_dp));
				lbox_grid_column.DataSource = lo_ds;
				lbox_grid_column.DataMember = "UPDMS_COM_PGM_GRID_COLUMN";
				lbox_grid_column.DataTextField = "Label_Nm";
				lbox_grid_column.DataValueField = "Label_Id";
				lbox_grid_column.DataBind();
			}

			ResetLabelIndex();
		}

		//이니셜 변경시
		protected void ddl_label_initial_SelectedIndexChanged(object sender, EventArgs e)
		{
			gs_page_mode = "I";
			SetLabelId();
		}

		#endregion

		#region 디테일 Method (AddLabel, DelLabel, UpLabel, DownLabel, ResetLabelIndex)

		//라벨추가
		private void AddLabel(string ps_text, string ps_value, string ps_excel_column)
		{
			string list_text = ps_text;

			if (!String.IsNullOrEmpty(ps_excel_column))
			{
				list_text = list_text + "(" + ps_excel_column + ")";
			}

			if (ps_value == "0")
			{
				list_text = "";
			}

			//lbox_grid_column의 마지막 인덱스와 ps_value를 합쳐서 value생성
			string prefix = (lbox_grid_column.Items.Count - 1).ToString() + "|";
			string surfix = "|" + ps_excel_column;


			ListItem items = new ListItem(list_text, prefix + ps_value + surfix);

			//선택된 아이템이 있으면 그 아이템 위에(없으면 맨밑에) 추가
			int li_pre_idx = lbox_grid_column.SelectedIndex;
			if (li_pre_idx > 0)
			{
				lbox_grid_column.Items.Insert(li_pre_idx, items);
			}
			else
			{
				lbox_grid_column.Items.Add(items);
			}

			ResetLabelIndex();
		}

		//라벨삭제
		private void DelLabel()
		{
			int num = lbox_grid_column.Items.Count - 1;

			for (int i = num; i > -1; i--)
			{
				if (lbox_grid_column.Items[i].Selected)
				{
					lbox_grid_column.Items.RemoveAt(i);
				}
			}

			ResetLabelIndex();
		}

		//라벨 위로
		private void UpLabel()
		{
			if (lbox_grid_column.SelectedIndex > -1)
			{
				int li_pre_idx = lbox_grid_column.SelectedIndex;
				if (li_pre_idx > 0)
				{
					lbox_grid_column.Items.Insert(li_pre_idx - 1, lbox_grid_column.Items[li_pre_idx]);
					lbox_grid_column.Items.RemoveAt(li_pre_idx + 1);
					lbox_grid_column.SelectedIndex = li_pre_idx - 1;
				}
			}

			ResetLabelIndex();
		}

		//라벨아래로
		private void DownLabel()
		{
			if (lbox_grid_column.SelectedIndex > -1)
			{
				int li_pre_idx = lbox_grid_column.SelectedIndex;
				if (li_pre_idx < lbox_grid_column.Items.Count - 1)
				{
					li_pre_idx++;
					lbox_grid_column.Items.Insert(li_pre_idx - 1, lbox_grid_column.Items[li_pre_idx]);
					lbox_grid_column.Items.RemoveAt(li_pre_idx + 1);
				}
			}

			ResetLabelIndex();
		}

		//라벨인덱스 재정렬
		private void ResetLabelIndex()
		{
			int num = lbox_grid_column.Items.Count;
			num--;
			for (int i = num; i > -1; i--)
			{
				string ls_label_nm = lbox_grid_column.Items[i].Text;
				int li_split_start = ls_label_nm.LastIndexOf("]");
				if (li_split_start > 0)
				{
					ls_label_nm = ls_label_nm.Substring(4, ls_label_nm.Length - 4);
				}

				lbox_grid_column.Items[i].Text = "[" + i.ToString().PadLeft(2, '0') + "]" + ls_label_nm;
			}
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, SearchProcess, InsertGridColumnProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_pgm_id", typeof(string), kw1);

			using (Com1019m_NT _Com1019m_NT = new Com1019m_NT())
			{
				lo_ds.Merge(_Com1019m_NT.SelectProcess(lo_dp));
			}

			GridView1.DataSource = lo_ds;
			GridView1.DataBind();

			lbl_result_count.Text = lo_ds.Tables["UPDMS_COM_PGM_GRID"].Rows.Count.ToString("#,###,##0");
		}

		//저장
		private void InsertProcess()
		{
			using (Com1019m_RT _Com1019m_RT = new Com1019m_RT())
			{
				int li_return = _Com1019m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Com1019m_RT _Com1019m_RT = new Com1019m_RT())
			{
				int li_return = _Com1019m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Com1019m_RT _Com1019m_RT = new Com1019m_RT())
			{
				int li_return = _Com1019m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";	//삭제되었습니다:삭제할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//검색
		private void SearchProcess()
		{
			gs_page_mode = "R";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
		}

		//그리드별 컬럼 등록
		private void InsertGridColumnProcess()
		{
			using (Com1019m_RT _Com1019m_RT = new Com1019m_RT())
			{
				int li_return = _Com1019m_RT.InsertColumnProcess(SetValueGridColumn());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		#endregion

		#region SetValue, ClearValue, SetValueGridColumn

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();
			lo_dp.AddProperty("Seq", typeof(string), lbl_pk.Text);
			lo_dp.AddProperty("Pgm_Id", typeof(string), ddl_search_pgm_id.SelectedValue);	//프로그램아이디
			lo_dp.AddProperty("Grid_Id", typeof(string), txt_grid_id.Text.Trim());			//그리드아이디
			lo_dp.AddProperty("Create_User", typeof(string), USER_ID);						//최초등록자
			lo_dp.AddProperty("Create_Dt", typeof(string), "");								//최초등록일
			lo_dp.AddProperty("Update_User", typeof(string), USER_ID);						//최종수정자
			lo_dp.AddProperty("Update_Dt", typeof(string), "");								//최종수정일

			return lo_dp;
		}

		//그리드 컬럼 값
		private string SetValueGridColumn()
		{
			string ls_result = "<UPDMS>";
			for (int i = 0; i < lbox_grid_column.Items.Count; i++)
			{
				string [] ls_values = lbox_grid_column.Items[i].Value.Split('|');
				string ls_label_id = "";
				string ls_col_nm = "";
				if (ls_values.Length > 1)
				{
					ls_label_id = ls_values[1];
					ls_col_nm = ls_values[2];
				}

				string send_pgm_id = "<Pgm_Id>" + ddl_search_pgm_id.SelectedValue + "</Pgm_Id>";
				string send_grid_id = "<Grid_Id>" + txt_grid_id.Text.Trim() + "</Grid_Id>";
				string send_col_idx = "<Col_Idx>" + i.ToString() + "</Col_Idx>";
				string send_label_id = "<Label_Id>" + ls_label_id + "</Label_Id>";
				string send_col_nm = "<Col_Nm>" + ls_col_nm + "</Col_Nm>";
				string send_create_user = "<Create_User>" + USER_ID + "</Create_User>";
				string send_update_user = "<Update_User>" + USER_ID + "</Update_User>";
					
				ls_result += 
					"<UPDMS_COM_PGM_GRID_COLUMN>"
						+ send_pgm_id
						+ send_grid_id
						+ send_col_idx
						+ send_label_id
						+ send_col_nm
						+ send_create_user
						+ send_update_user
					+ "</UPDMS_COM_PGM_GRID_COLUMN>";
			}
			ls_result = ls_result + "</UPDMS>";
			
			return ls_result;
		}		

		//ClearValue
		private void ClearValue()
		{
			lbl_pk.Text = "";
			h_no.Value = "";
			h_pgm_id.Value = "";
			txt_grid_id.Text = "";

			lbox_grid_column.Items.Clear();	//그리드별 컬럼관리 초기화
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":	// 처음 페이지로드시
					table_grid.Visible = false;
					table_grid_column.Visible = false;
					break;
				case "R":	// 검색버튼 클릭시
					table_grid.Visible = true;
					table_grid_column.Visible = false;
					break;
				case "I":	// 그리드아이디 클릭시
					table_grid.Visible = true;
					table_grid_column.Visible = true;
					break;
			}
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}
	

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text = (e.Row.RowIndex + 1).ToString();
			}
			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView1);
			sGv.RowSpanGridView(GridView1, 3);
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			gs_page_mode = "I";

			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			//row.Cells[0].Text.ToString();										//0.체크박스
			h_no.Value = row.Cells[1].Text.ToString();							//1.번호
			lbl_pk.Text = gv.DataKeys[row.RowIndex].Values["Seq"].ToString();	//2.Seq
			h_seq.Value = lbl_pk.Text;
			h_pgm_id.Value = row.Cells[3].Text.ToString();						//3.Pgm_Id
			txt_grid_id.Text = lbtn_rc.Text;									//4.Ctrl_Id(template)
			h_grid_id.Value = txt_grid_id.Text;

			SetGridColumn(txt_grid_id.Text);
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//추가
		protected void lbtn_add_label_Click(object sender, EventArgs e)
		{
			gs_page_mode = "I";
			AddLabel(ddl_label_id.SelectedItem.Text, ddl_label_id.SelectedValue, txt_col_nm.Text.Trim());
		}

		//삭제
		protected void lbtn_del_label_Click(object sender, EventArgs e)
		{
			gs_page_mode = "I";
			DelLabel();
		}

		//위로
		protected void lbtn_up_label_Click(object sender, EventArgs e)
		{
			gs_page_mode = "I";
			UpLabel();
		}

		//아래로
		protected void lbtn_down_label_Click(object sender, EventArgs e)
		{
			gs_page_mode = "I";
			DownLabel();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			if (global.CheckSaveMode("UPDMS_COM_PGM_GRID", "Seq", lbl_pk.Text.Trim()))
			{
				UpdateProcess();
			}
			else
			{
				InsertProcess();
			}
		}

		//저장 - 그리드별 컬럼
		protected void ibtn_save_grid_column_Click(object sender, EventArgs e)
		{
			InsertGridColumnProcess();
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");
			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");
				LinkButton lbtn_rc = (LinkButton)GridView1.Rows[i].FindControl("lbtn_rc");	//그리드아이디

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();

					sb.Append("<UPDMS_COM_PGM_GRID>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("<Pgm_Id>" + ddl_search_pgm_id.SelectedValue + "</Pgm_Id>");
					sb.Append("<Grid_Id>" + lbtn_rc.Text.Trim() + "</Grid_Id>");
					sb.Append("</UPDMS_COM_PGM_GRID>");
				}
			}
			sb.Append("</UPDMS>");

			//Base.AppFramework.SMEventLog.WriteDataLog("ibtn_delete_Click", sb.ToString());
			DeleteProcess(sb.ToString());
		}

		#endregion

	}
}
